package com.ljy.task;

import com.ljy.entity.LeaseOrders;
import com.ljy.mapper.LeaseOrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class LeaseOrderTask {
    @Autowired
    LeaseOrdersMapper leaseOrdersMapper;

    //定时处理超时订单，每天凌晨2点执行，订单超过24小时并且未付款的即为超时订单
    @Scheduled(cron = "0 0 2 * * ? ")
    //@PostConstruct可以在项目启动时执行一次该方法
    @PostConstruct
    public void processTimeoutOrder(){
        log.info("执行超时检查");
        LocalDateTime timeout=LocalDateTime.now().minusDays(1);
        List<LeaseOrders> timeoutOrders = leaseOrdersMapper.getTimeoutOrder(timeout, LeaseOrders.PENDING_PAYMENT);
        for (LeaseOrders order:timeoutOrders){
            //订单状态为已取消
            order.setStatus(LeaseOrders.CANCELLED);
            //取消原因
            order.setReason("订单一直未支付，超时取消订单");
            order.setCancelTime(LocalDateTime.now());
            leaseOrdersMapper.update(order);
            log.info("订单{}超时",order.getId());
        }
    }

    @Scheduled(cron = "0 0/5 * * * ? ")
    public void processLeaseTimeOrder(){
        log.info("执行判断租赁到期");
        //每隔5分钟执行一次,判断租赁是否到期
        LocalDateTime timeout=LocalDateTime.now();
        List<LeaseOrders> timeoutOrders = leaseOrdersMapper.getLeaseTimeout(timeout, LeaseOrders.USING);
        for (LeaseOrders order:timeoutOrders){
            //订单状态为已完成
            order.setStatus(LeaseOrders.COMPLETED);
            leaseOrdersMapper.update(order);
            log.info("订单{}已完成",order.getId());
        }
        //TODO 给到期用户发通知
        //TODO 给web管理员发通知
    }


}
